package com.example.myapplication7;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        //注册广播接收者
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        //是否处于充电状态
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
        //充电方式（共有两种，分别是通过AC充电和通过USB端口进行充电）
        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        //判断当前电池电量
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float)scale;
        //打印相关信息
        Log.i("BatteryLevelReceiver",  "是否在充电:" + isCharging + "；" + "是否usb充电:" + usbCharge + "；" + "是否ac充电:" + acCharge);
        if(isCharging==true){
            Log.d("BatteryLevelReceiver","正在充电" );
        }
        Log.i("BatteryLevelReceiver","电量："+batteryPct);
        if(batteryPct<=0.2){
            Log.d("BatteryLevelReceiver","电量较低" );
        }
        if(batteryPct>0.2){
            Log.d("BatteryLevelReceiver","电量充足" );
        }

    }
}
